﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BillingSystem.DataSetMainTableAdapters;

namespace BillingSystem
{
    /// <summary> The Magic form </summary>
    public partial class FormMain : Form
    {
        #region Идентификаторы

        /// <summary> Главный DataSet </summary>
        private DataSetMain dataSetMain;

        // Набор BindingSource'ов вкладки 1
        private BindingSource accountsBindingSource;
        private BindingSource clientsBindingSource;
        private BindingSource numbersBindingSource;
        private BindingSource connectionsBindingSource;
        private BindingSource operationsBindingSource;

        // Набор BindingSource'ов вкладки 2
        private BindingSource tariffsBindingSource;
        private BindingSource rateBindingSource;
        private BindingSource directionsBindingSource;

        // Набор TableAdapter вкладки 1
        private ACCOUNTSTableAdapter accountsTableAdapter = new ACCOUNTSTableAdapter();
        private CLIENTSTableAdapter clientsTableAdapter = new CLIENTSTableAdapter();
        private NUMBERSTableAdapter numbersTableAdapter = new NUMBERSTableAdapter();
        private OPERATIONSTableAdapter operationsTableAdater = new OPERATIONSTableAdapter();
        
        // Набор TableAdapter вкладки 2
        private RATE_SCHEDULETableAdapter rateTableAdapter = new RATE_SCHEDULETableAdapter();
        private TARIFFSTableAdapter tariffsTableAdapter = new TARIFFSTableAdapter();
        private DIRECTIONSTableAdapter directionsTableAdapter = new DIRECTIONSTableAdapter();
        private CONNECTIONSTableAdapter connectionsTableAdapter = new CONNECTIONSTableAdapter();
        

        #endregion

        /// <summary>Конструктор формы</summary>
        public FormMain()
        {
            InitializeComponent();

            dataSetMain = new DataSetMain();
            dataSetMain.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;

            clientsTableAdapter.ClearBeforeFill = true;
            numbersTableAdapter.ClearBeforeFill = true;
            accountsTableAdapter.ClearBeforeFill = true;
            
            connectionsTableAdapter.ClearBeforeFill = true;

            rateTableAdapter.ClearBeforeFill = true;            
            tariffsTableAdapter.ClearBeforeFill = true;

            accountsBindingSource = new BindingSource(dataSetMain, "ACCOUNTS");
            clientsBindingSource = new BindingSource(dataSetMain, "CLIENTS");
            numbersBindingSource = new BindingSource(dataSetMain, "NUMBERS");
            rateBindingSource = new BindingSource(dataSetMain, "RATE_SCHEDULE");
            tariffsBindingSource = new BindingSource(dataSetMain, "TARIFFS");
            directionsBindingSource = new BindingSource(dataSetMain, "DIRECTIONS");
            connectionsBindingSource = new BindingSource(dataSetMain, "CONNECTIONS");
            operationsBindingSource = new BindingSource(dataSetMain, "OPERATIONS");
        }

        /// <summary>Действия после загрузки формы</summary>
        private void FormMain_Load(object sender, EventArgs e)
        {
            accountsTableAdapter.Fill(this.dataSetMain.ACCOUNTS);
            directionsTableAdapter.Fill(this.dataSetMain.DIRECTIONS);
            tariffsTableAdapter.Fill(this.dataSetMain.TARIFFS);
            SetControls(accountsBindingSource, clientsBindingSource, numbersBindingSource, tariffsBindingSource);
            SetGrid();
        }

        #region Установка компонентов

        public void SetControls(BindingSource accountsBindingSource, BindingSource clientsBindingSource, 
                                BindingSource numbersBindingSource, BindingSource tariffsBindingSource)
        {
            try
            {
                //this.textBoxAddress.DataBindings.Add("Text", drv, "ADDRESS", false);
                //this.textBoxAgreement.DataBindings.Add("Text", drv, "ACCOUNT_NUMBER", false, 
                //    DataSourceUpdateMode, null, "N0");
                //this.textBoxAgreementDate.DataBindings.Add("Text", drv, "CONCLUSION_DATE", false, 
                //    DataSourceUpdateMode.OnValidation, null, "d");
                //this.textBoxFIO.DataBindings.Add("Text", drv, "FIO", false, 
                //    DataSourceUpdateMode.OnValidation);
                //this.textBoxPassport.DataBindings.Add("Text", drv, "PASSPORT", false, 
                //    DataSourceUpdateMode.OnValidation, null, "N0");

                listBoxClients.DataSource = accountsBindingSource;                
                listBoxClients.DisplayMember = "ACCOUNT_NUMBER";

                listBoxTel.DataSource = numbersBindingSource;
                listBoxTel.DisplayMember = "NUM";

                //
                listBoxTariffs.DataSource = tariffsBindingSource;
                listBoxTariffs.DisplayMember = "NAME";
                //




                //listBoxClients.DataBindings.Add(
                //    new System.Windows.Forms.Binding("SelectedItem", accountsBindingSource, 
                //        "ACCOUNT_NUMBER", true, DataSourceUpdateMode.OnPropertyChanged));
                //listBoxClients.DataBindings.Add(
                //    new System.Windows.Forms.Binding("SelectedValue", accountsBindingSource,
                //        "ACCOUNT_NUMBER", true, DataSourceUpdateMode.OnPropertyChanged));
                
            }
            catch (NullReferenceException exc) { MessageBox.Show("SetControls null" + exc.ToString()); }
        }

        /// <summary>Установка конпонентов пользовательской информации</summary>
        /// <param name="clientsBindingSource"></param>
        private void SetClientTextBoxes(BindingSource clientsBindingSource)
        {
            DataRowView drv = (DataRowView)clientsBindingSource.Current;
            if (accountsBindingSource.Current == null ||
                ((DataRowView)accountsBindingSource.Current)["CLIENT_ID"] is DBNull)
            {
                SetControlsEnabled(false);
                return;
            }

            if (clientsBindingSource.Current == null) return;

            this.textBoxAddress.Text = drv["ADDRESS"].ToString();
            this.textBoxAgreement.Text = drv["ACCOUNT_NUMBER"].ToString();
            this.textBoxFIO.Text = drv["FIO"].ToString();
            this.textBoxPassport.Text = drv["PASSPORT"].ToString();
            this.textBoxAgreementDate.Text = drv["CONCLUSION_DATE"].ToString();
            labelMoney.Text = drv["MONEY"].ToString();
        }

        /// <summary>Установка Enabled полей пользователя</summary>
        /// <param name="value"></param>
        private void SetControlsEnabled(bool value)
        {
            this.textBoxAddress.Enabled = value;
            this.textBoxAgreement.Enabled = value;
            this.textBoxAgreementDate.Enabled = value;
            this.textBoxFIO.Enabled = value;
            this.textBoxPassport.Enabled = value;
        }

        /// <summary>Настройка DataGridView тарифной сетки</summary>
        /// <param name="bs">Необходимый BindingSource</param>
        private void SetGrid()
        {
            DataGridViewComboBoxColumn nameDataGridViewTextBoxColumn = new DataGridViewComboBoxColumn();
            DataGridViewTextBoxColumn priceDataGridViewTextBoxColumn = new DataGridViewTextBoxColumn();
            DataGridViewComboBoxColumn prefixDataGridViewTextBoxColumn = new DataGridViewComboBoxColumn();
            // 
            // nameDataGridViewTextBoxColumn
            // 
            nameDataGridViewTextBoxColumn.DataPropertyName = "DIRECTION_ID";
            nameDataGridViewTextBoxColumn.DataSource = this.directionsBindingSource;
            nameDataGridViewTextBoxColumn.DisplayMember = "NAME";
            nameDataGridViewTextBoxColumn.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.Nothing;
            nameDataGridViewTextBoxColumn.HeaderText = "Название";
            nameDataGridViewTextBoxColumn.Name = "nameDataGridViewTextBoxColumn";
            nameDataGridViewTextBoxColumn.ReadOnly = true;
            nameDataGridViewTextBoxColumn.Resizable = System.Windows.Forms.DataGridViewTriState.True;
            nameDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
            nameDataGridViewTextBoxColumn.ValueMember = "DIRECTION_ID";
            nameDataGridViewTextBoxColumn.Width = 200;
            // 
            // priceDataGridViewTextBoxColumn
            // 
            priceDataGridViewTextBoxColumn.DataPropertyName = "PRICE";
            priceDataGridViewTextBoxColumn.HeaderText = "Стоимость";
            priceDataGridViewTextBoxColumn.Name = "priceDataGridViewTextBoxColumn";
            priceDataGridViewTextBoxColumn.ReadOnly = true;
            priceDataGridViewTextBoxColumn.Width = 100;
            // 
            // prefixDataGridViewTextBoxColumn
            // 
            prefixDataGridViewTextBoxColumn.DataPropertyName = "DIRECTION_ID";
            prefixDataGridViewTextBoxColumn.DataSource = this.directionsBindingSource;
            prefixDataGridViewTextBoxColumn.DisplayMember = "PREFIX";
            prefixDataGridViewTextBoxColumn.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.Nothing;
            prefixDataGridViewTextBoxColumn.HeaderText = "Код";
            prefixDataGridViewTextBoxColumn.Name = "prefixDataGridViewTextBoxColumn";
            prefixDataGridViewTextBoxColumn.ReadOnly = true;
            prefixDataGridViewTextBoxColumn.Resizable = System.Windows.Forms.DataGridViewTriState.True;
            prefixDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
            prefixDataGridViewTextBoxColumn.ValueMember = "DIRECTION_ID";
            prefixDataGridViewTextBoxColumn.Width = 80;
            //
            // dataGridViewMaterials
            //
            dataGridViewDirections.AllowUserToAddRows = false;
            dataGridViewDirections.AllowUserToDeleteRows = false;
            dataGridViewDirections.AllowUserToResizeRows = false;
            dataGridViewDirections.AutoGenerateColumns = false;
            dataGridViewDirections.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            dataGridViewDirections.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            prefixDataGridViewTextBoxColumn,
            nameDataGridViewTextBoxColumn,
            priceDataGridViewTextBoxColumn});
            dataGridViewDirections.DataSource = this.rateBindingSource;
            dataGridViewDirections.MultiSelect = false;
            dataGridViewDirections.ReadOnly = true;
            dataGridViewDirections.RowHeadersVisible = false;
            dataGridViewDirections.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
        }

        //private Set

        #endregion

        #region Редактирование клиентской информации

        /// <summary> Перерасчет денюшек всех клиентов </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRecountMoney_Click(object sender, EventArgs e)
        {
            FormShowAllBalances frab = new FormShowAllBalances();
            frab.ShowForm(dataSetMain);
        }

        /// <summary>Обработка события добавление клиента</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddClient_Click(object sender, EventArgs e)
        {
            clientsBindingSource.AddNew();
            if (AddEditClient())
            {
                SetClientTextBoxes(clientsBindingSource);
                accountsTableAdapter.Fill(this.dataSetMain.ACCOUNTS);
                accountsBindingSource.MoveLast();
            }
        }

        /// <summary>Обработка события редактирование клиента</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClientEdit_Click(object sender, EventArgs e)
        {
            if (AddEditClient())
            {
                SetClientTextBoxes(clientsBindingSource);
            }
        }

        /// <summary>Создание и редактирование клиента</summary>
        /// <returns>Результат операции</returns>
        private bool AddEditClient()
        {
            try
            {
                FormEditClient fec = new FormEditClient();
                if (fec.ShowForm(clientsBindingSource))
                {
                    clientsBindingSource.EndEdit();
                    clientsTableAdapter.Update(dataSetMain.CLIENTS);
                    return true;
                }
                return false;
            }
            catch (ConstraintException exc)
            {
                MessageBox.Show("Не удалось изменить информацию клиента");
                clientsBindingSource.CancelEdit();
                return false;
            } 
        }

        /// <summary>Удаление клиента</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelClient_Click(object sender, EventArgs e)
        {
            try
            {
                clientsTableAdapter.Delete((decimal)((DataRowView)clientsBindingSource.Current)["CLIENT_ID"]);
                clientsBindingSource.RemoveCurrent();
                clientsBindingSource.EndEdit();
                //clientsTableAdapter.Update(dataSetMain.CLIENTS);
                accountsBindingSource.RemoveCurrent();
                listBoxClients_SelectedIndexChanged(null, null);
                SetClientTextBoxes(clientsBindingSource);
            }
            catch (Exception) { MessageBox.Show("Невозможно удалить клиента."); }
        }

        /// <summary>Обработка события смены выделенного договора</summary>
        private void listBoxClients_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ((DataRowView)accountsBindingSource.Current != null)
            {
                try
                {
                    DataRowView drv = (DataRowView)accountsBindingSource.Current;
                    decimal client_id = (decimal)((DataRowView)accountsBindingSource.Current)["CLIENT_ID"];
                    clientsTableAdapter.FillById(dataSetMain.CLIENTS, client_id);
                    numbersTableAdapter.FillByClientId(dataSetMain.NUMBERS, client_id);
                    SetClientTextBoxes(clientsBindingSource);
                    SetControlsEnabled(true);
                }
                catch (NullReferenceException exc) { MessageBox.Show("Нет выбранных элементов"); }
            }
            else
            {
                SetControlsEnabled(false);
            }
        }

        /// <summary> Поиск клиента </summary>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (textBoxSearch.Text == "" || textBoxSearch.Text == "*")
            {
                accountsTableAdapter.Fill(dataSetMain.ACCOUNTS);
                return;
            }

            if (radioBtnAgreement.Checked == true)
                accountsTableAdapter.FillByAccountNum(dataSetMain.ACCOUNTS, decimal.Parse(textBoxSearch.Text));
            if (radioBtnTel.Checked == true)
                accountsTableAdapter.FillByNumber(dataSetMain.ACCOUNTS, decimal.Parse(textBoxSearch.Text));
            if (radioBtnFIO.Checked == true)
                accountsTableAdapter.FillByFIO(dataSetMain.ACCOUNTS, textBoxSearch.Text + "%");
            if (radioBtnPassport.Checked == true)
                accountsTableAdapter.FillByPASSPORT(dataSetMain.ACCOUNTS, decimal.Parse(textBoxSearch.Text));
            if (radioBtnAddress.Checked == true)
                accountsTableAdapter.FillByADDRESS(dataSetMain.ACCOUNTS, textBoxSearch.Text);

        }

        #endregion 

        #region Редактирование телефонов клиента

        private void btnAddTel_Click(object sender, EventArgs e)
        {
            try
            {
                numbersBindingSource.AddNew();
                FormEditTelNumber fetn =
                    new FormEditTelNumber(tariffsBindingSource, (decimal)((DataRowView)clientsBindingSource.Current)["CLIENT_ID"]);
                if (fetn.ShowForm(numbersBindingSource))
                {
                    numbersBindingSource.EndEdit();
                    numbersTableAdapter.Update(dataSetMain.NUMBERS);
                    listBoxClients_SelectedIndexChanged(null, null);
                }
            }
            catch (ConstraintException exc)
            {
                MessageBox.Show("Не удалось изменить номер");
                numbersBindingSource.CancelEdit();
            }
        }

        /// <summary>Редактирование информации о телефоне</summary>
        private void btnEditTel_Click(object sender, EventArgs e)
        {
            try
            {
                //numbersBindingSource.AddNew();
                FormEditTelNumber fetn =
                    new FormEditTelNumber(tariffsBindingSource, (decimal)((DataRowView)clientsBindingSource.Current)["CLIENT_ID"]);
                if (fetn.ShowForm(numbersBindingSource))
                {
                    numbersBindingSource.EndEdit();
                    numbersTableAdapter.Update(dataSetMain.NUMBERS);
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show("Не удалось изменить номер");
                numbersBindingSource.CancelEdit();
            }
        }

        /// <summary>Удаление телефонного номера</summary>
        private void btnDelTel_Click(object sender, EventArgs e)
        {
            if (numbersBindingSource.Current == null) return;
            numbersTableAdapter.Delete((decimal)((DataRowView)numbersBindingSource.Current)["NUMBER_ID"]);
            numbersBindingSource.RemoveCurrent();
            numbersBindingSource.EndEdit();
        }


        #endregion   

        #region Редактирование тарифов

        /// <summary>Добавление редактирование тарифа</summary>
        /// <returns>Возвращает результат действия над тарифом(да/нет)</returns>
        private bool AddEditTariff()
        {
            try
            {
                FormEditTariff fec = new FormEditTariff();
                if (fec.ShowForm(tariffsBindingSource))
                {
                    tariffsBindingSource.EndEdit();
                    tariffsTableAdapter.Update(dataSetMain.TARIFFS);
                    return true;
                }
                return false;
            }
            catch (ConstraintException exc)
            {
                MessageBox.Show("Не удалось изменить информацию о тарифе" + exc.Message);
                tariffsBindingSource.CancelEdit();
                return false;
            }
        }

        /// <summary>Добавление нового тарифа</summary>
        private void btnAddTariff_Click(object sender, EventArgs e)
        {
            tariffsBindingSource.AddNew();
            if (AddEditTariff())
            {
                tariffsTableAdapter.Fill(this.dataSetMain.TARIFFS);
                tariffsBindingSource.MoveLast();
            }
            else
            {
                tariffsBindingSource.CancelEdit();
                tariffsBindingSource.MoveLast();
            }
        }

        /// <summary>Редактирования названия таррифа</summary>
        private void btnEditTariff_Click(object sender, EventArgs e)
        {
            if (!AddEditTariff()) tariffsBindingSource.CancelEdit();
        }

        /// <summary>Удаление выбранного тарифа</summary>
        private void btnDelTariff_Click(object sender, EventArgs e)
        {
            tariffsTableAdapter.Delete((decimal)((DataRowView)tariffsBindingSource.Current)["TARIFF_ID"]); 
            tariffsBindingSource.RemoveCurrent();
            tariffsBindingSource.EndEdit();
            //tariffsTableAdapter.Update(dataSetMain.TARIFFS);
        }

        /// <summary>Обработка события смены выделенного тарифа</summary>
        private void listBoxTariffs_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ((DataRowView)tariffsBindingSource.Current != null)
            {
                try
                {
                    DataRowView drv = (DataRowView)tariffsBindingSource.Current;
                    if (drv["NAME"] is DBNull) return;
                    decimal tariff_id = (decimal)drv["TARIFF_ID"];
                    rateTableAdapter.FillByTariffId(dataSetMain.RATE_SCHEDULE, tariff_id);
                    dataGridViewDirections.Refresh();
                    dataGridViewDirections.Enabled = true; 
                }
                catch (NullReferenceException exc) { 
                    dataGridViewDirections.Enabled = false; 
                    MessageBox.Show("Проблемы с выборкой тарифной сетки"); 
                }
            }
            else
            {
                dataGridViewDirections.Enabled = false;
            }
        }

        /// <summary>Добавление направления в тарифе</summary>
        private void btnAddDirection_Click(object sender, EventArgs e)
        {
            rateBindingSource.AddNew();
            try
            {
                FormEditRateScheduleItem fersi = 
                    new FormEditRateScheduleItem(directionsBindingSource,
                        (decimal)((DataRowView)tariffsBindingSource.Current)["TARIFF_ID"]);
                if (fersi.ShowForm(rateBindingSource))
                {
                    rateBindingSource.EndEdit();
                    rateTableAdapter.Update(dataSetMain.RATE_SCHEDULE);
                }
            }
            catch (ConstraintException exc)
            {
                MessageBox.Show("Не удалось изменить информацию" + exc.Message);
                rateBindingSource.CancelEdit();
            }
        }

        /// <summary>Редактирование направления в тарифе</summary>
        private void btnEditDirection_Click(object sender, EventArgs e)
        {
            try
            {
                FormEditRateScheduleItem fersi =
                    new FormEditRateScheduleItem(directionsBindingSource,
                        (decimal)((DataRowView)tariffsBindingSource.Current)["TARIFF_ID"]);
                if (fersi.ShowForm(rateBindingSource))
                {
                    rateBindingSource.EndEdit();
                    rateTableAdapter.Update(dataSetMain.RATE_SCHEDULE);
                }
            }
            catch (ConstraintException exc)
            {
                MessageBox.Show("Не удалось изменить информацию" + exc.Message);
                rateBindingSource.CancelEdit();
            }
        }

        /// <summary>И удаление направления в тарифе</summary>
        private void btnDelDirection_Click(object sender, EventArgs e)
        {
            if (rateBindingSource.Current != null)
            {
                rateBindingSource.RemoveCurrent();
                rateTableAdapter.Update(dataSetMain.RATE_SCHEDULE);
            }
        }

        /// <summary>Импорт тарифной сетки из XML</summary>
        private void btnImportTariff_Click(object sender, EventArgs e)
        {
            if (tariffsBindingSource.Current == null) return;

            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = "C:\\";
            openFileDialog1.Filter = "xml files (*.xml)|*.xml";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                XMLBoss xmlboss = new XMLBoss();
                xmlboss.ReadXml(dataSetMain.Tables["RATE_SCHEDULE"], openFileDialog1.FileName);
                
                decimal n = (decimal)((DataRowView)tariffsBindingSource.Current)["TARIFF_ID"];

                foreach (DataRow dr in dataSetMain.RATE_SCHEDULE.Rows)
                {
                    dr["TARIFF_ID"] = n;
                }
                rateTableAdapter.Update(dataSetMain.RATE_SCHEDULE);
                dataGridViewDirections.Refresh();
            }
        }

        /// <summary>Экспорт тарифной сетки в XML</summary>
        private void btnExportTariff_Click(object sender, EventArgs e)
        {
            if (tariffsBindingSource.Current == null) return;
            
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.InitialDirectory = "C:\\";
            saveFileDialog.Filter = "XML files (*.xml)|*.xml";
            saveFileDialog.FilterIndex = 1;
            saveFileDialog.RestoreDirectory = true;

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                rateBindingSource.EndEdit();
                XMLBoss xmlboss = new XMLBoss();
                xmlboss.WriteXml(dataSetMain.RATE_SCHEDULE, saveFileDialog.FileName);
            }
        }

        #endregion



        private void btnStatTel_Click(object sender, EventArgs e)
        {
            try
            {
                connectionsTableAdapter.FillByNumId(dataSetMain.CONNECTIONS,
                    (decimal)((DataRowView)numbersBindingSource.Current)["NUMBER_ID"]);
                FormNumberStat fns = new FormNumberStat();
                fns.ShowForm(connectionsBindingSource);
            }
            catch (NullReferenceException exc) {
                MessageBox.Show("Нет выбранного номера");
            }
        }


        private void btnViewDirections_Click(object sender, EventArgs e)
        {
            FormEditDirections fmDir = new FormEditDirections(this.dataSetMain, this.directionsTableAdapter);
            fmDir.Show(directionsBindingSource);
        }

        private void btnPutMoney_Click(object sender, EventArgs e)
        {
            FormPutMoney fpm = new FormPutMoney();
            int sum;
            if ((sum = fpm.ShowForm()) > 0)
            {
                decimal c_id = (decimal)((DataRowView)clientsBindingSource.Current)["CLIENT_ID"];
                clientsTableAdapter.PutMoney(sum, c_id);
                operationsTableAdater.InsertQuery(sum, c_id); 
                clientsTableAdapter.Update(dataSetMain.CLIENTS);
                operationsTableAdater.Update(dataSetMain.OPERATIONS);
                listBoxClients_SelectedIndexChanged(null, null);
            }
        }

        private void btnStat_Click(object sender, EventArgs e)
        {
            try
            {
                decimal client_id = (decimal)((DataRowView)clientsBindingSource.Current)["CLIENT_ID"];
                connectionsTableAdapter.FillByClientId(dataSetMain.CONNECTIONS, client_id);
                operationsTableAdater.FillByClientId(dataSetMain.OPERATIONS, client_id);
                FormReport fr = new FormReport();
                fr.ShowForm(connectionsBindingSource, operationsBindingSource,
                    (DataRowView)clientsBindingSource.Current);
            }
            catch (NullReferenceException exc)
            {
                MessageBox.Show("Нет выбранного клиента");
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            FormDraft fd = new FormDraft();
            fd.ShowForm((DataRowView)clientsBindingSource.Current, dataSetMain);
        }
    }
}

       